<template>
  <div class="app-container">
    <el-card class="box-card">
      <div class="filter-container">
        <el-form :inline="true" :model="queryParams" ref="queryForm">
          <el-form-item label="管理员" prop="admin_id">
            <el-select v-model="queryParams.admin_id" placeholder="请选择管理员" clearable style="width: 200px">
              <el-option
                v-for="admin in adminList"
                :key="admin.id"
                :label="admin.username"
                :value="admin.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="操作类型" prop="action">
            <el-select v-model="queryParams.action" placeholder="请选择操作类型" clearable style="width: 200px">
              <el-option
                v-for="action in actionList"
                :key="action"
                :label="action"
                :value="action"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="关键词" prop="search">
            <el-input
              v-model="queryParams.search"
              placeholder="请输入关键词"
              clearable
              style="width: 200px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="操作时间" prop="dateRange">
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd"
              style="width: 240px"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleQuery">搜索</el-button>
            <el-button @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="el-icon-delete"
              size="mini"
              @click="handleClear"
            >清空日志</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-s-data"
              size="mini"
              @click="handleStatistics"
            >统计分析</el-button>
          </el-col>
        </el-row>
      </div>

      <el-table 
        v-loading="loading" 
        :data="logList"
        @sort-change="handleSortChange"
      >
        <el-table-column label="ID" align="center" prop="id" width="80" />
        <el-table-column
          label="管理员"
          align="center"
        >
          <template #default="scope">
            {{ scope.row.admin ? scope.row.admin.username : '-' }}
          </template>
        </el-table-column>
        <el-table-column
          label="操作类型"
          align="center"
          prop="action"
        >
          <template #default="scope">
            <el-tag :type="getActionTagType(scope.row.action)">
              {{ scope.row.action }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="操作详情"
          align="center"
          prop="details"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          label="IP地址"
          align="center"
          prop="ip"
          width="130"
        />
        <el-table-column
          label="操作时间"
          align="center"
          prop="create_time"
          width="180"
          sortable="custom"
        />
      </el-table>

      <el-pagination
        :page-sizes="[10, 20, 50, 100]"
        :page-size="queryParams.per_page"
        :current-page="queryParams.page"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <!-- 统计分析对话框 -->
    <el-dialog title="日志统计分析" :visible.sync="statsDialogVisible" width="80%">
      <div v-loading="statsLoading">
        <div class="filter-container">
          <el-form :inline="true" :model="statsQueryParams">
            <el-form-item label="时间范围">
              <el-date-picker
                v-model="statsDateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="yyyy-MM-dd"
                style="width: 240px"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="getStatistics">查询</el-button>
            </el-form-item>
          </el-form>
        </div>

        <el-row :gutter="20">
          <el-col :span="24">
            <div ref="dailyChart" style="height: 300px"></div>
          </el-col>
        </el-row>

        <el-row :gutter="20" style="margin-top: 20px">
          <el-col :span="12">
            <el-card class="box-card">
              <div slot="header" class="clearfix">
                <span>操作类型分布</span>
              </div>
              <div ref="actionChart" style="height: 300px"></div>
            </el-card>
          </el-col>
          <el-col :span="12">
            <el-card class="box-card">
              <div slot="header" class="clearfix">
                <span>管理员操作次数</span>
              </div>
              <el-table :data="statistics.admin_distribution" border style="width: 100%">
                <el-table-column prop="username" label="管理员" />
                <el-table-column prop="count" label="操作次数" />
              </el-table>
            </el-card>
          </el-col>
        </el-row>
      </div>
    </el-dialog>

    <!-- 清空日志对话框 -->
    <el-dialog title="清空日志" :visible.sync="clearDialogVisible" width="30%">
      <el-form :model="clearForm">
        <el-form-item label="清空方式">
          <el-radio-group v-model="clearForm.type">
            <el-radio :label="'all'">清空所有日志</el-radio>
            <el-radio :label="'before'">清空指定日期前日志</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="日期" v-if="clearForm.type === 'before'">
          <el-date-picker
            v-model="clearForm.before_date"
            type="date"
            placeholder="选择日期"
            value-format="yyyy-MM-dd"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="clearDialogVisible = false">取消</el-button>
        <el-button type="danger" @click="confirmClear">确认清空</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getAdminLogs, getLogActions, getLogAdmins, getLogStatistics, clearAdminLogs } from '@/api/admin-log'
import * as echarts from 'echarts'

export default {
  name: 'AdminLog',
  data() {
    return {
      loading: false,
      logList: [],
      total: 0,
      dateRange: [],
      actionList: [],
      adminList: [],
      queryParams: {
        page: 1,
        per_page: 20,
        admin_id: '',
        action: '',
        search: '',
        start_date: '',
        end_date: ''
      },
      // 统计相关
      statsDialogVisible: false,
      statsLoading: false,
      statsDateRange: [],
      statsQueryParams: {
        start_date: '',
        end_date: ''
      },
      statistics: {
        daily_stats: [],
        action_distribution: [],
        admin_distribution: []
      },
      dailyChart: null,
      actionChart: null,
      // 清空相关
      clearDialogVisible: false,
      clearForm: {
        type: 'all',
        before_date: ''
      }
    }
  },
  created() {
    this.getList()
    this.getActionList()
    this.getAdminList()
  },
  methods: {
    // 获取日志列表
    getList() {
      this.loading = true
      
      // 处理日期范围
      if (this.dateRange && this.dateRange.length === 2) {
        this.queryParams.start_date = this.dateRange[0]
        this.queryParams.end_date = this.dateRange[1]
      } else {
        this.queryParams.start_date = ''
        this.queryParams.end_date = ''
      }
      
      getAdminLogs(this.queryParams).then(response => {
        if (response.code === 0) {
          this.logList = response.data.items
          this.total = response.data.total
        } else {
          this.$message.error(response.message || '获取日志列表失败')
        }
        this.loading = false
      }).catch((error) => {
        console.error('获取日志列表失败', error)
        this.$message.error('获取日志列表失败')
        this.loading = false
      })
    },
    
    // 获取操作类型列表
    getActionList() {
      getLogActions().then(response => {
        if (response.code === 0) {
          this.actionList = response.data
        }
      }).catch(error => {
        console.error('获取操作类型列表失败', error)
      })
    },
    
    // 获取管理员列表
    getAdminList() {
      getLogAdmins().then(response => {
        if (response.code === 0) {
          this.adminList = response.data
        }
      }).catch(error => {
        console.error('获取管理员列表失败', error)
      })
    },
    
    // 查询
    handleQuery() {
      this.queryParams.page = 1
      this.getList()
    },
    
    // 重置查询
    resetQuery() {
      this.dateRange = []
      this.$refs.queryForm.resetFields()
      this.queryParams.page = 1
      this.getList()
    },
    
    // 排序变化
    handleSortChange(column) {
      // 这个API暂时没有提供排序功能，可以保留但不处理
    },
    
    // 每页条数变化
    handleSizeChange(size) {
      this.queryParams.per_page = size
      this.getList()
    },
    
    // 页码变化
    handleCurrentChange(page) {
      this.queryParams.page = page
      this.getList()
    },
    
    // 获取操作类型标签样式
    getActionTagType(action) {
      const typeMap = {
        '登录': 'info',
        '新增': 'success',
        '修改': 'warning',
        '删除': 'danger',
        '导出': 'primary',
        '清空日志': 'danger'
      }
      return typeMap[action] || ''
    },
    
    // 打开统计分析对话框
    handleStatistics() {
      this.statsDialogVisible = true
      this.getStatistics()
    },
    
    // 获取统计数据
    getStatistics() {
      this.statsLoading = true
      
      // 处理日期范围
      if (this.statsDateRange && this.statsDateRange.length === 2) {
        this.statsQueryParams.start_date = this.statsDateRange[0]
        this.statsQueryParams.end_date = this.statsDateRange[1]
      } else {
        this.statsQueryParams.start_date = ''
        this.statsQueryParams.end_date = ''
      }
      
      getLogStatistics(this.statsQueryParams).then(response => {
        if (response.code === 0) {
          this.statistics = response.data
          this.$nextTick(() => {
            this.initDailyChart()
            this.initActionChart()
          })
        }
        this.statsLoading = false
      }).catch((error) => {
        console.error('获取统计数据失败', error)
        this.$message.error('获取统计数据失败')
        this.statsLoading = false
      })
    },
    
    // 初始化日志趋势图表
    initDailyChart() {
      if (!this.statistics.daily_stats || this.statistics.daily_stats.length === 0) return
      
      if (!this.dailyChart) {
        this.dailyChart = echarts.init(this.$refs.dailyChart)
      }
      
      const dates = this.statistics.daily_stats.map(item => item.date)
      const counts = this.statistics.daily_stats.map(item => item.count)
      
      const option = {
        title: {
          text: '日志操作趋势',
          left: 'center'
        },
        tooltip: {
          trigger: 'axis',
        },
        xAxis: {
          type: 'category',
          data: dates
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            data: counts,
            type: 'line',
            smooth: true
          }
        ]
      }
      
      this.dailyChart.setOption(option)
    },
    
    // 初始化操作类型分布图表
    initActionChart() {
      if (!this.statistics.action_distribution || this.statistics.action_distribution.length === 0) return
      
      if (!this.actionChart) {
        this.actionChart = echarts.init(this.$refs.actionChart)
      }
      
      const data = this.statistics.action_distribution.map(item => {
        return {
          name: item.action,
          value: item.count
        }
      })
      
      const option = {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 10,
          data: data.map(item => item.name)
        },
        series: [
          {
            name: '操作类型',
            type: 'pie',
            radius: ['50%', '70%'],
            avoidLabelOverlap: false,
            label: {
              show: false,
              position: 'center'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '18',
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: false
            },
            data: data
          }
        ]
      }
      
      this.actionChart.setOption(option)
    },
    
    // 打开清空日志对话框
    handleClear() {
      this.clearDialogVisible = true
      this.clearForm = {
        type: 'all',
        before_date: ''
      }
    },
    
    // 确认清空日志
    confirmClear() {
      const data = {}
      if (this.clearForm.type === 'before' && this.clearForm.before_date) {
        data.before_date = this.clearForm.before_date
      }
      
      this.$confirm(`确认${this.clearForm.type === 'all' ? '清空所有日志' : '清空指定日期前的日志'}吗？此操作不可恢复`, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        clearAdminLogs(data).then(response => {
          if (response.code === 0) {
            this.$message.success('日志清空成功')
            this.clearDialogVisible = false
            this.getList()
          } else {
            this.$message.error(response.message || '清空日志失败')
          }
        }).catch(error => {
          console.error('清空日志失败', error)
          this.$message.error('清空日志失败')
        })
      }).catch(() => {})
    },
    
    // 窗口大小变化时重绘图表
    handleResize() {
      if (this.dailyChart) {
        this.dailyChart.resize()
      }
      if (this.actionChart) {
        this.actionChart.resize()
      }
    }
  },
  mounted() {
    window.addEventListener('resize', this.handleResize)
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize)
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.filter-container {
  margin-bottom: 20px;
}

.mb8 {
  margin-bottom: 8px;
}
</style> 